"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Textarea } from "@/components/ui/textarea"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { writingQuestions } from "@/lib/questions-data"
import { useUser } from "@/lib/user-context"
import { useToast } from "@/components/ui/use-toast"

export default function WritingPage() {
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0)
  const [answer, setAnswer] = useState("")
  const [isSubmitted, setIsSubmitted] = useState(false)
  const [completedQuestions, setCompletedQuestions] = useState<number[]>([])
  const router = useRouter()
  const { user } = useUser()
  const { toast } = useToast()

  const currentQuestion = writingQuestions[currentQuestionIndex]
  const progress = (completedQuestions.length / writingQuestions.length) * 100

  // 如果用户未登录，重定向到首页
  useEffect(() => {
    if (!user) {
      toast({
        title: "请先登录",
        description: "您需要登录后才能进行练习",
        variant: "destructive",
      })
      router.push("/")
    }
  }, [user, router, toast])

  // 提交答案
  const submitAnswer = () => {
    if (!answer.trim()) {
      toast({
        title: "请输入您的答案",
        description: "答案不能为空",
        variant: "destructive",
      })
      return
    }

    // 保存答案到本地存储
    const storedWritingAnswers = JSON.parse(localStorage.getItem("writingAnswers") || "{}")
    storedWritingAnswers[currentQuestion.id] = answer
    localStorage.setItem("writingAnswers", JSON.stringify(storedWritingAnswers))

    // 更新已完成问题
    const newCompletedQuestions = [...completedQuestions]
    if (!newCompletedQuestions.includes(currentQuestion.id)) {
      newCompletedQuestions.push(currentQuestion.id)
    }
    setCompletedQuestions(newCompletedQuestions)

    // 更新进度
    const progress = {
      writing: {
        completed: newCompletedQuestions.length === writingQuestions.length,
        answeredCount: newCompletedQuestions.length,
        total: writingQuestions.length,
      },
    }

    const storedProgress = JSON.parse(localStorage.getItem("progress") || "{}")
    localStorage.setItem("progress", JSON.stringify({ ...storedProgress, ...progress }))

    setIsSubmitted(true)

    toast({
      title: "提交成功",
      description: "您的答案已保存",
    })
  }

  // 下一题
  const nextQuestion = () => {
    if (currentQuestionIndex < writingQuestions.length - 1) {
      setCurrentQuestionIndex(currentQuestionIndex + 1)

      // 检查下一题是否已有答案
      const storedWritingAnswers = JSON.parse(localStorage.getItem("writingAnswers") || "{}")
      const nextQuestionId = writingQuestions[currentQuestionIndex + 1].id
      setAnswer(storedWritingAnswers[nextQuestionId] || "")
      setIsSubmitted(!!storedWritingAnswers[nextQuestionId])
    } else {
      // 所有问题都已完成
      if (completedQuestions.length === writingQuestions.length) {
        toast({
          title: "练习完成！",
          description: `您已完成所有写作练习`,
        })

        // 跳转到结果页面
        router.push(
          "/practice/result?type=writing&answeredCount=" +
            completedQuestions.length +
            "&total=" +
            writingQuestions.length,
        )
      } else {
        toast({
          title: "还有未完成的题目",
          description: "请完成所有写作题目",
        })
      }
    }
  }

  // 加载已保存的答案
  useEffect(() => {
    const storedWritingAnswers = JSON.parse(localStorage.getItem("writingAnswers") || "{}")
    setAnswer(storedWritingAnswers[currentQuestion.id] || "")
    setIsSubmitted(!!storedWritingAnswers[currentQuestion.id])

    // 加载已完成的问题
    const completedIds = Object.keys(storedWritingAnswers).map((id) => Number.parseInt(id))
    setCompletedQuestions(completedIds)
  }, [currentQuestion.id])

  if (!user) {
    return null
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-2xl font-bold mb-4">写作练习</h1>
        <Progress value={progress} className="h-2" />
        <p className="text-sm text-muted-foreground mt-2">
          已完成 {completedQuestions.length} / {writingQuestions.length}
        </p>
      </div>

      <Card className="mb-6">
        <CardHeader>
          <CardTitle>{currentQuestion.title}</CardTitle>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="question">
            <TabsList className="mb-4">
              <TabsTrigger value="question">题目</TabsTrigger>
              <TabsTrigger value="example">范文</TabsTrigger>
            </TabsList>
            <TabsContent value="question">
              <div className="space-y-4">
                <p>{currentQuestion.description}</p>
                <p className="text-sm text-muted-foreground">{currentQuestion.requirements}</p>
                <Textarea
                  placeholder="请在此输入您的答案..."
                  value={answer}
                  onChange={(e) => setAnswer(e.target.value)}
                  className="min-h-[200px]"
                />
              </div>
            </TabsContent>
            <TabsContent value="example">
              <div className="p-4 border rounded-md bg-muted/50">
                <p className="whitespace-pre-line">{currentQuestion.example}</p>
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
        <CardFooter className="flex justify-between">
          <Button onClick={submitAnswer} disabled={isSubmitted}>
            {isSubmitted ? "已提交" : "提交答案"}
          </Button>
          <Button onClick={nextQuestion} variant="outline">
            {currentQuestionIndex < writingQuestions.length - 1 ? "下一题" : "完成"}
          </Button>
        </CardFooter>
      </Card>
    </div>
  )
}
